package com.zhanghe.im.util;

import com.zhanghe.im.attributes.Attributes;
import com.zhanghe.im.session.Session;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtil {

    private static final Map<String,Channel> userIdChannelMap = new ConcurrentHashMap<>();

    private static final Map<String,ChannelGroup> channelGroupMap = new ConcurrentHashMap<>();

    /**
     * 绑定session
     * @param session
     * @param channel
     */
    public static void bindSession(Session session,Channel channel){
        userIdChannelMap.put(session.getUserId(),channel);
        channel.attr(Attributes.SESSION).set(session);
    }

    public static void unbindSession(Session session,Channel channel){
        if (hasLogin(channel)) {
            userIdChannelMap.remove(session.getUserId());
            channel.attr(Attributes.SESSION).set(null);
        }
    }

    public static boolean hasLogin(Channel channel){
        return channel.hasAttr(Attributes.SESSION) && channel.attr(Attributes.SESSION).get()!=null;
    }

    public static Session getSession(Channel channel){
        return channel.attr(Attributes.SESSION).get();
    }

    public static Channel getChannel(String userId) {
        return userIdChannelMap.get(userId);
    }

    public static void addChannelGroup(String groupId,ChannelGroup group){
        channelGroupMap.put(groupId,group);
    }

    public static ChannelGroup getChannelGroup(String groupId){
        return channelGroupMap.get(groupId);
    }
}
